package com.java.cg.item.service;

import com.alibaba.fastjson.JSON;
import com.java.cg.goods.entity.Category;
import com.java.cg.goods.entity.Sku;
import com.java.cg.goods.entity.Spu;
import com.java.cg.goods.feign.GoodsApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangli
 * @since 2020/2/15 16:55
 */
@Service
public class ItemService {
	@Autowired
	private TemplateEngine engine;
	@Autowired
	private GoodsApi goodsApi;
	@Value("${pagepath}")
	private String pagePath;

	public void createHtml(Long spuId) {
		//初始化运行上下文
		Context context = new Context();
		//设置数据模型
		context.setVariables(this.loadData(spuId));

		PrintWriter printWriter = null;
		try {
			//把静态文件生成到服务器本地
			// 指定生成静态页的位置(路径)
			String path = ItemService.class.getResource("/").getPath()+"/items";
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 生成静态页面的文件名(通过Id更新)
			File dist = new File(file, spuId + ".html");
			printWriter = new PrintWriter(dist, "UTF-8");

			//参数:1.指定模板 2.模板所需的数据模型 3.输出文件对象
			engine.process("item", context, printWriter);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (printWriter != null) {
				printWriter.close();
			}
		}
	}

	/**
	 * 查询spu List<Sku> category
	 */
	private Map<String, Object> loadData(Long spuId) {
		Spu spu = goodsApi.findSpuById(spuId);

		Category category1 = goodsApi.findCategoryById(spu.getCategory1Id());
		Category category2 = goodsApi.findCategoryById(spu.getCategory2Id());
		Category category3 = goodsApi.findCategoryById(spu.getCategory3Id());

		List<Sku> skuList = goodsApi.getSkusBySpuId(spuId);

		Map<String, Object> map = new HashMap<>();
		// spu
		map.put("spu", spu);
		// 商品分类
		map.put("category1", category1);
		map.put("category2", category2);
		map.put("category3", category3);
		// skuList
		map.put("skuList", skuList);
		// 图片
		if (spu.getImages() != null) {
			map.put("images", spu.getImages().split(","));
		}
		//规格参数
		map.put("specificationList", JSON.parseObject(spu.getSpecItems(), Map.class));
		return map;
	}
}
